package com.hongye.area.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.hongye.area.dao.AreaDao;

import com.hongye.area.pojo.CityPojo;
import com.zxy.common.utils.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zxy.common.utils.PageUtils;

import com.hongye.area.dao.CityDao;
import com.hongye.area.entity.CityEntity;
import com.hongye.area.service.CityService;
import org.springframework.transaction.annotation.Transactional;


@Service("cityService")
public class CityServiceImpl extends ServiceImpl<CityDao, CityEntity> implements CityService {

    @Autowired
    CityDao cityDao;
    @Autowired
    AreaDao areaDao;


    @Override
    public PageUtils queryPage(Map<String, Object> params, Integer pid) {
        List<CityPojo> arr = cityDao.findCityAndCounty(pid);
        //总记录数
        int size = arr.size();
        //当前页数
        Integer page = Integer.valueOf(params.get("page").toString());
        //每页记录数
        Integer limit = Integer.valueOf(params.get("limit").toString());
        //选取
        List<CityPojo> collect = arr.stream().skip(limit * (page - 1)).limit(limit).collect(Collectors.toList());

        return new PageUtils(collect,size,limit,page);

    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public R updateCityState( Integer id, Integer state) {
        //查询省级id
        CityEntity cityEntity = cityDao.selectById(id);
        //判断状态
        if (state == cityEntity.getState() ) {
            return R.error(500,"状态以改变");
        }
        //修改城市状态
        int i = cityDao.updataCityState(id,state);


        //增减
        int increment = 0;
        if (state > 0) {
            increment = 1;//启动
        }else {
            increment = -1;//禁用
        }
        //修改地区启动和禁用
        int i2 = areaDao.updataAddStateCityReduceDisCity(cityEntity.getPid(),increment);
        return R.ok();
    }


    @Override
    public List<CityEntity> threeLevel(Integer pid) {
        QueryWrapper<CityEntity> qw = new QueryWrapper<>();
        qw.eq("pid",pid);
        //禁用时前台不显示
        qw.eq("state",1);
        List<CityEntity> cityEntities = cityDao.selectList(qw);

        return cityEntities;
    }

}